package com.example.mydemo

import android.content.Context
import android.graphics.SurfaceTexture
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import com.example.mydemo.texture.TriangleTexture
import com.example.mydemo.utils.WeakHandler

class MyTextureView(context: Context, attrs: AttributeSet? = null) : TextureView(context, attrs), SurfaceTextureListener {

    companion object {
        private const val TAG = "MyTextureView"
    }

    private var mGLThread: GLHandlerThread? = null
    private var mGlHandler: WeakHandler? = null
    private var mMyRender: MyRender? = null

    private var isInit = false

    init {
        surfaceTextureListener = this
        isOpaque = false
    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        Log.d(TAG, "onSurfaceTextureAvailable :  $surface  width  : $width   height : $height")
        isInit = true

        mMyRender = MyRender(TriangleTexture())

        // 创建一个线程，作为GL线程
        mGLThread = GLHandlerThread(mMyRender).apply {
            mSurfaceTexture = surface
            start()

            //创建handle操作GLHandlerThread
            mGlHandler = WeakHandler(looper, this)
        }

        //发送初始化GL线程
        mGlHandler?.sendEmptyMessage(GLHandlerThread.MSG_INIT)
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
        Log.d(TAG, "onSurfaceTextureSizeChanged :  $surface  width  : $width   height : $height")
        if (isInit) {
            Message.obtain().apply {
                what = GLHandlerThread.MSG_ON_SIZE_CHANGE
                obj = intArrayOf(width, height)

                mGlHandler?.sendMessage(this)
            }
        }
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
        Log.d(TAG, "onSurfaceTextureUpdated :  $surface")
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        Log.d(TAG, "onSurfaceTextureDestroyed :  $surface")

        if (isInit && mGLThread?.isAlive == true) {
            mGlHandler?.sendEmptyMessage(GLHandlerThread.MSG_ON_DESTROY)
        }

        mGLThread?.apply {
            mSurfaceTexture = null
            quitSafely()
        }
        mGLThread = null

        isInit = false
        surfaceTextureListener = null
        return true //true 系统自己回收SurfaceTexture， false 需要自己主动回收
    }

}